package com.platform.toutiao.config;

import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.collect.Maps;
import com.platform.entity.MpMsgEntity;
import com.platform.service.MpMsgService;
import com.platform.toutiao.api.TouTiaoServiceHttpClient;

@Component
public class TouTiaoConfiguration {
    private static Map<Integer, TouTiaoServiceHttpClient> ttServices = Maps.newHashMap();
    
    @Autowired
    private MpMsgService mpMsgService;

	@PostConstruct
    public void init() {
    	Map<String, Object> params = Maps.newHashMap();
    	params.put("type", 2);
    	List<MpMsgEntity> mpMsgs = mpMsgService.queryList(params);
    	for(MpMsgEntity mpMsg:mpMsgs) {
    		putTtService(mpMsg);
        }
    }    
    
    public TouTiaoServiceHttpClient putTtService(MpMsgEntity mpMsg) {
    	TouTiaoConfig config = new TouTiaoConfig ();
        config.setAppId(mpMsg.getAppId());
        config.setSecret(mpMsg.getMpSecret());
        TouTiaoServiceHttpClient service = new TouTiaoServiceHttpClient(config);
        ttServices.put(mpMsg.getId(), service);
        return service;
    }
    
    public TouTiaoServiceHttpClient getTtService(Integer appId) {
    	TouTiaoServiceHttpClient ttService = ttServices.get(appId);
        if (ttService == null) {
    		MpMsgEntity mpMsg = mpMsgService.queryObject(appId);
    		ttService = putTtService(mpMsg);
        }
        return ttService;
    }
}
